//
//  UIImage+Common.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "UIImage+Common.h"



@implementation UIImage (Common)

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size corner:(CGFloat)cornerRadius{
    if (color == nil) {
        return nil;
    }
    UIGraphicsBeginImageContextWithOptions(size,NO, [UIScreen mainScreen].scale);
    UIBezierPath* roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0,size.width,size.height) cornerRadius:cornerRadius];
    [color setFill];
    [roundedRectanglePath fill];
    UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
+ (UIImage *)gradientColorImageFromColors:(NSArray*)colors
                             gradientType:(LM_GradientType)gradientType
                                  imgSize:(CGSize)imgSize {

    NSMutableArray *ar = [NSMutableArray array];

    for(UIColor *c in colors) {

        [ar addObject:(id)c.CGColor];

    }

    UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSaveGState(context);

    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);

    CGPoint start;

    CGPoint end;

    switch (gradientType) {

        case LM_GradientTypeTopToBottom:

            start = CGPointMake(0.0, 0.0);

            end = CGPointMake(0.0, imgSize.height);

            break;

        case LM_GradientTypeLeftToRight:

            start = CGPointMake(0.0, 0.0);

            end = CGPointMake(imgSize.width, 0.0);

            break;

        case LM_GradientTypeUpleftToLowright:

            start = CGPointMake(0.0, 0.0);

            end = CGPointMake(imgSize.width, imgSize.height);

            break;

        case LM_GradientTypeUprightToLowleft:

            start = CGPointMake(imgSize.width, 0.0);

            end = CGPointMake(0.0, imgSize.height);

            break;

        default:

            break;

    }

    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    CGGradientRelease(gradient);

    CGContextRestoreGState(context);

    CGColorSpaceRelease(colorSpace);

    UIGraphicsEndImageContext();

    return image;
}
//
//
//
//
//+ (UIImage *)imageWithView:(UIView *)view{
//
//    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [UIScreen mainScreen].scale);
//    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
//    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//
//    return image;
//}
//
//-(UIImage*)imageByResizeToSize:(CGSize)dstSize
//{
//    CGImageRef imgRef = self.CGImage;
//    // the below values are regardless of orientation : for UIImages from Camera, width>height (landscape)
//    CGSize  srcSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); // not equivalent to self.size (which is dependant on the imageOrientation)!
//
//    /* Don't resize if we already meet the required destination size. */
//    if (CGSizeEqualToSize(srcSize, dstSize)) {
//        return self;
//    }
//
//    CGFloat scaleRatio = dstSize.width / srcSize.width;
//    UIImageOrientation orient = self.imageOrientation;
//    CGAffineTransform transform = CGAffineTransformIdentity;
//    switch(orient) {
//
//        case UIImageOrientationUp: //EXIF = 1
//            transform = CGAffineTransformIdentity;
//            break;
//
//        case UIImageOrientationUpMirrored: //EXIF = 2
//            transform = CGAffineTransformMakeTranslation(srcSize.width, 0.0);
//            transform = CGAffineTransformScale(transform, -1.0, 1.0);
//            break;
//
//        case UIImageOrientationDown: //EXIF = 3
//            transform = CGAffineTransformMakeTranslation(srcSize.width, srcSize.height);
//            transform = CGAffineTransformRotate(transform, M_PI);
//            break;
//
//        case UIImageOrientationDownMirrored: //EXIF = 4
//            transform = CGAffineTransformMakeTranslation(0.0, srcSize.height);
//            transform = CGAffineTransformScale(transform, 1.0, -1.0);
//            break;
//
//        case UIImageOrientationLeftMirrored: //EXIF = 5
//            dstSize = CGSizeMake(dstSize.height, dstSize.width);
//            transform = CGAffineTransformMakeTranslation(srcSize.height, srcSize.width);
//            transform = CGAffineTransformScale(transform, -1.0, 1.0);
//            transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
//            break;
//
//        case UIImageOrientationLeft: //EXIF = 6
//            dstSize = CGSizeMake(dstSize.height, dstSize.width);
//            transform = CGAffineTransformMakeTranslation(0.0, srcSize.width);
//            transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
//            break;
//
//        case UIImageOrientationRightMirrored: //EXIF = 7
//            dstSize = CGSizeMake(dstSize.height, dstSize.width);
//            transform = CGAffineTransformMakeScale(-1.0, 1.0);
//            transform = CGAffineTransformRotate(transform, M_PI_2);
//            break;
//
//        case UIImageOrientationRight: //EXIF = 8
//            dstSize = CGSizeMake(dstSize.height, dstSize.width);
//            transform = CGAffineTransformMakeTranslation(srcSize.height, 0.0);
//            transform = CGAffineTransformRotate(transform, M_PI_2);
//            break;
//
//        default:
//            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
//
//    }
//
//    /////////////////////////////////////////////////////////////////////////////
//    // The actual resize: draw the image on a new context, applying a transform matrix
//    UIGraphicsBeginImageContextWithOptions(dstSize, NO, self.scale);
//
//    CGContextRef context = UIGraphicsGetCurrentContext();
//
//       if (!context) {
//           return nil;
//       }
//
//    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
//        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
//        CGContextTranslateCTM(context, -srcSize.height, 0);
//    } else {
//        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
//        CGContextTranslateCTM(context, 0, -srcSize.height);
//    }
//
//    CGContextConcatCTM(context, transform);
//
//    // we use srcSize (and not dstSize) as the size to specify is in user space (and we use the CTM to apply a scaleRatio)
//    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, srcSize.width, srcSize.height), imgRef);
//    UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//
//    return resizedImage;
//}
//
////生成二维码
//+ (UIImage *)generateQRCodeWithString:(NSString *)string Size:(CGFloat)size
//{
//    //创建过滤器
//    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//    //过滤器恢复默认
//    [filter setDefaults];
//    //给过滤器添加数据<字符串长度893>
//    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//    [filter setValue:data forKey:@"inputMessage"];
//    //获取二维码过滤器生成二维码
//    CIImage *image = [filter outputImage];
//    UIImage *img = [self createNonInterpolatedUIImageFromCIImage:image WithSize:size];
//    return img;
//}
//
////二维码清晰
//+ (UIImage *)createNonInterpolatedUIImageFromCIImage:(CIImage *)image WithSize:(CGFloat)size
//{
//    CGRect extent = CGRectIntegral(image.extent);
//    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
//
//    //创建bitmap
//    size_t width = CGRectGetWidth(extent)*scale;
//    size_t height = CGRectGetHeight(extent)*scale;
//    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
//    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
//    CIContext *context = [CIContext contextWithOptions:nil];
//    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
//    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
//    CGContextScaleCTM(bitmapRef, scale, scale);
//    CGContextDrawImage(bitmapRef, extent, bitmapImage);
//
//    //保存图片
//    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
//    CGColorSpaceRelease(cs);
//    CGContextRelease(bitmapRef);
//    CGImageRelease(bitmapImage);
//
//    UIImage * result = [UIImage imageWithCGImage:scaledImage];
//    CGImageRelease(scaledImage);
//    return result;
//}
//
//
//+ (UIImage *)qrImageForString:(NSString *)string imageSize:(CGFloat)imageSize logoImage:(UIImage *)logoImage logoImageSize:(CGFloat)logoImageSize
//{
//    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//    [filter setDefaults];
//    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//    [filter setValue:data forKey:@"inputMessage"];//通过kvo方式给一个字符串，生成二维码
//    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];//设置二维码的纠错水平，越高纠错水平越高，可以污损的范围越大
//    CIImage *outPutImage = [filter outputImage];//拿到二维码图片
//    return [[self alloc] createNonInterpolatedUIImageFormCIImage:outPutImage withSize:imageSize logoImage:logoImage logoImageSize:logoImageSize];
//}
//
//- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size logoImage:(UIImage *)logoImage logoImageSize:(CGFloat)logoImageSize
//{
//    CGRect extent = CGRectIntegral(image.extent);
//    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
//    // 1.创建bitmap;
//    size_t width = CGRectGetWidth(extent) * scale;
//    size_t height = CGRectGetHeight(extent) * scale;
//    //创建一个DeviceGray颜色空间
//    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
//    //CGBitmapContextCreate(void * _Nullable data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef  _Nullable space, uint32_t bitmapInfo)
//    //width：图片宽度像素
//    //height：图片高度像素
//    //bitsPerComponent：每个颜色的比特值，例如在rgba-32模式下为8
//    //bitmapInfo：指定的位图应该包含一个alpha通道。
//    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
//    CIContext *context = [CIContext contextWithOptions:nil];
//    //创建CoreGraphics image
//    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
//
//    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
//    CGContextScaleCTM(bitmapRef, scale, scale);
//    CGContextDrawImage(bitmapRef, extent, bitmapImage);
//
//    // 2.保存bitmap到图片
//    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
//    CGContextRelease(bitmapRef);
//    CGImageRelease(bitmapImage);
//    CGColorSpaceRelease(cs);
//
//    //原图
//    UIImage *outputImage = [UIImage imageWithCGImage:scaledImage];
//    outputImage = [UIImage specialColorImage:outputImage withRed:178 green:110 blue:43];
//
//    CGImageRelease(scaledImage);
//    if (logoImage)
//    {
//        //给二维码加 logo 图
//        UIGraphicsBeginImageContextWithOptions(outputImage.size, NO, [[UIScreen mainScreen] scale]);
//        [outputImage drawInRect:CGRectMake(0,0 , size, size)];
//        //logo图
//        //把logo图画到生成的二维码图片上，注意尺寸不要太大（最大不超过二维码图片的%30），太大会造成扫不出来
//        [logoImage drawInRect:CGRectMake((size-logoImageSize)/2.0, (size-logoImageSize)/2.0, logoImageSize, logoImageSize)];
//        UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//        return newPic;
//    }
//    return outputImage;
//}
//
//////修改图片颜色
////- (UIImage *)imageChangeColor:(UIColor *)color
////{
////    //获取画布
////    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
////    //画笔沾取颜色
////    [color setFill];
////    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
////    UIRectFill(bounds);
////    //绘制一次
////    [self drawInRect:bounds blendMode:kCGBlendModeOverlay alpha:1.0f];
////    //再绘制一次
////    [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
////    //获取图片
////    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
////    UIGraphicsEndImageContext();
////    return img;
////}
//
//void ProviderReleaseData (void *info, const void *data, size_t size){
//     free((void*)data);
//}
//
////改变二维码颜色
//+ (UIImage *)specialColorImage:(UIImage *)image withRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue {
//    const int imageWidth = image.size.width;
//    const int imageHeight = image.size.height;
//    size_t bytesPerRow = imageWidth * 4;
//    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
//
//    //Create context
//    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
//    CGContextRef contextRef = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpaceRef, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
//    CGContextDrawImage(contextRef, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
//
//    //Traverse pixe
//    int pixelNum = imageWidth * imageHeight;
//    uint32_t* pCurPtr = rgbImageBuf;
//    for (int i = 0; i < pixelNum; i++, pCurPtr++){
//        if ((*pCurPtr & 0xFFFFFF00) < 0x99999900){
//            //Change color
//            uint8_t* ptr = (uint8_t*)pCurPtr;
//            ptr[3] = red; //0~255
//            ptr[2] = green;
//            ptr[1] = blue;
//        }else{
//            uint8_t* ptr = (uint8_t*)pCurPtr;
//            ptr[0] = 0;
//        }
//    }
//    CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight,ProviderReleaseData);
//    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpaceRef,
//                                        kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProviderRef,
//                                        NULL, true, kCGRenderingIntentDefault);
//    CGDataProviderRelease(dataProviderRef);
//    UIImage* img = [UIImage imageWithCGImage:imageRef];
//
//    //Release
//    CGImageRelease(imageRef);
//    CGContextRelease(contextRef);
//    CGColorSpaceRelease(colorSpaceRef);
//    return img;
//}


#define kBitsPerComponent (8)
#define kBitsPerPixel (32)


#pragma mark - CVPixelBufferRef 转换 UIimage

/**
 CVPixelBufferRef 转换为UIimage

 @param pixelBufffer 图片的CVPixelBufferRef
 @return UIimage
 */
+(UIImage*)pixelBufferToImage:(CVPixelBufferRef) pixelBufffer
{
    CIImage *ciImage = [CIImage imageWithCVPixelBuffer:pixelBufffer];

    CIContext *temporaryContext = [CIContext contextWithOptions:nil];
    CGImageRef videoImage = [temporaryContext
                       createCGImage:ciImage
                       fromRect:CGRectMake(0, 0,
                              CVPixelBufferGetWidth(pixelBufffer),
                              CVPixelBufferGetHeight(pixelBufffer))];

    UIImage *uiImage = [UIImage imageWithCGImage:videoImage];
    CGImageRelease(videoImage);
    return uiImage;
}

@end
